package org.example.dao;

import org.example.entity.User;
import org.example.util.JDBCUtils;

import java.sql.*;
import java.util.List;

/**
 * 用户数据访问实现类
 * 调取数据库内数据
 */
public class UserDAOImpl implements UserDAO {
    /**
     * 查询一个用户
     *
     * @param u
     * @return
     */
    @Override
    public User selectOne(User u) {
        Connection conn = null;
        User user = null;
        try {
            conn = JDBCUtils.getConn();
            PreparedStatement ps = conn.prepareStatement("select *from user where user_id = ?");
            ps.setInt(1, u.getUserID());
            ResultSet rs = ps.executeQuery();
            if (rs.next()) { //判断结果集中是否有数据
                user = new User();
                user.setUserID(rs.getInt("user_id"));
                user.setUsername(rs.getString("username"));
                user.setEmail(rs.getString("email"));
                user.setPhone(rs.getString("phone"));
                user.setCreateTime(rs.getTimestamp("create_time").toLocalDateTime());
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return user;
    }

    @Override
    public List<User> selectAll() {
        return null;
    }

    /**
     * 添加用户信息
     * @param user
     * @return
     */
    @Override
    public int insertUser(User user) {
        int i = 0;
        try {
            Connection conn = JDBCUtils.getConn();
            String sql = "insert into user(username,password,role,phone,create_time)values(?,?,?,?,?)";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPassword());
            ps.setInt(3, user.getRole());
            ps.setString(4, user.getPhone());
            ps.setTimestamp(5, Timestamp.valueOf(user.getCreateTime()));
            //执行sql语句
            i = ps.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        return i;
    }

    @Override
    public int deleteUser(User user) {
        return 0;
    }

    @Override
    public int updateUser(User user) {
        return 0;
    }
}
